package com.up.stores.controller;

import com.up.stores.entity.Address;
import com.up.stores.service.IAddressService;
import com.up.stores.until.JsonResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;

@Api(tags="地址模块")
@RestController
@RequestMapping("addresses")
public class AddressController extends BaseController {
    @Autowired
    private IAddressService addressService;

    @ApiOperation(value="添加地址")
    @PostMapping("add_new_address")
    public JsonResult<Void> addNewAddress(Address address, HttpSession session) {
        // 从Session中获取id,type和username
        Integer uid = getuidFromSession(session);
        String type = getTypeFromSession(session);
        String username = getUsernameFromSession(session);
        // 调用业务对象的方法执行业务
        addressService.addNewAddress(uid, type, username, address);
        // 响应成功
        return new JsonResult<Void>(OK);
    }
    @ApiOperation(value="获取当前用户收发货地址", notes="若当前用户为Admin类型，则表示的是收货地址，若是Buss类型，则表示的是发货地址")
    @GetMapping({"/"})
    public JsonResult<List<Address>> getByUid(HttpSession session) {
        Integer uid = getuidFromSession(session);
        String type = getTypeFromSession(session);
        List<Address> data = addressService.getByUid(uid, type);
        return new JsonResult<>(OK, data);
    }

    @ApiOperation(value="修改地址信息", notes="根据session中的Type会判断当前的用户类型")
    @PutMapping("change")
    public JsonResult<Void> change(Address address, HttpSession session) {
        Integer uid = getuidFromSession(session);
        String type = getTypeFromSession(session);
        String username = getUsernameFromSession(session);
        addressService.changeAddress(address.getAddId(), uid, type, username, address);
        return new JsonResult<Void>(OK);
    }

    @ApiOperation(value="设置默认地址")
    @PutMapping("set_default")
    public JsonResult<Void> setDefault(Integer addId, HttpSession session) {
        Integer uid = getuidFromSession(session);
        String type = getTypeFromSession(session);
        String username = getUsernameFromSession(session);
        addressService.setDefault(addId, uid, type, username);
        return new JsonResult<Void>(OK);
    }

    @ApiOperation(value="删除地址")
    @DeleteMapping("delete")
    public JsonResult<Void> delete(Integer addId, HttpSession session) {
        Integer uid = getuidFromSession(session);
        String type = getTypeFromSession(session);
        String username = getUsernameFromSession(session);
        addressService.delete(addId, uid, type, username);
        return new JsonResult<Void>(OK);
    }
}